package com.ziJing.multithreading.sync.interview01;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.LockSupport;

/**
 * @program Multithreading
 * @description:
 * @author: zhangbo
 * @create: 2022/05/04 00:20
 */
public class T08_Semaphore {

    List<Object> list = Collections.synchronizedList(new LinkedList<>());


    int size() {
        return list.size();
    }


    void add(Object ele) {
        list.add(ele);
    }


    Object get(int index) {
        return list.get(index);
    }

    static Thread t1 = null, t2 = null;


    public static void main(String[] args) {
        T08_Semaphore c = new T08_Semaphore();

        Semaphore semaphore = new Semaphore(1);


        t1 = new Thread(() -> {

            System.out.println("t1 启动");
            try {
                semaphore.acquire();
                for (int i = 0; i < 5; i++) {
                    c.add(new Object());
                    System.out.println("add " + i);
                }
                semaphore.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            try {
                t2.start();
                t2.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            try {
                semaphore.acquire();
                for (int i = 5; i < 10; i++) {
                    c.add(new Object());
                    System.out.println("add " + i);
                }
                semaphore.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }


        }, "t1");


        t2 = new Thread(() -> {
            System.out.println("t2 启动");

            try {
                semaphore.acquire();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println("t2 结束");
            semaphore.release();


        }, "t2");


        t1.start();
//        t2.start();



    }
}
